import PkgCommon.PkgUser;
import com.google.protobuf.TextFormat;
import com.google.protobuf.util.JsonFormat;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;

public class EtyMain {
	public static void main(String[] aArg) {
		System.out.println("A test for converting proto to json.");
		PkgUser.PhtList_Respond.Builder oRpd = PkgUser.PhtList_Respond.newBuilder();
		oRpd.setCode(0x3001);
		oRpd.setCommand("Usr_Pht_List");
		oRpd.setResult("0");
		oRpd.setMessage("成功");
		PkgUser.PhtList_Item.Builder oItm = PkgUser.PhtList_Item.newBuilder();
		oItm.setPhtIdntifr("1");
		oItm.setPhtStatus("1");
		oItm.setUrlFinalztion("https://www.baidu.com/1.jpg");
		oRpd.addList(oItm);
		// proto to json
		try {
			JSONObject jDat = new JSONObject(JsonFormat.printer().preservingProtoFieldNames().print(oRpd)); // 字段的下划线
			System.out.println(jDat);
			// 或者
			//System.out.println(TextFormat.printer().escapingNonAscii(false).printToString(oRpd.build()));
			//System.out.println(TextFormat.printToUnicodeString(oRpd.build())); // 废弃
		} catch (Exception e) {
			System.out.println("Proto data error: " + e.getMessage());
		}

		byte[] aBfr = oRpd.build().toByteArray();
		int nBfr = aBfr.length;
		PkgUser.MsgCommon_Respond oPkg = null;

		try {
			oPkg = PkgUser.MsgCommon_Respond.parseFrom(new ByteArrayInputStream(aBfr, 0, 5));
		} catch (Exception e) {
			System.out.println("Proto data error: " + e.getMessage());
		}
		if (oPkg != null) {
			switch (oPkg.getCode()) {
				case 0x3001: {
					try {
						PkgUser.PhtList_Respond oNew = PkgUser.PhtList_Respond.parseFrom(aBfr);
						System.out.println(TextFormat.printer().escapingNonAscii(false).printToString(oNew));
					} catch (Exception e) {
						System.out.println("Respond is error: " + e.getMessage());
					}
				}
				break;
			}
		}
		oRpd = null;
		// json to proto
        JSONObject jDat = new JSONObject("{\"result\":\"0\",\"code\":12289,\"message\":\"成功\",\"list\":[{\"pht_status\":\"1\",\"url_finalztion\":\"https://www.baidu.com/1.jpg\",\"pht_idntifr\":\"1\"}],\"command\":\"Usr_Pht_List\"}");
		oRpd = PkgUser.PhtList_Respond.newBuilder();
		try {
			JsonFormat.parser().merge(jDat.toString(), oRpd);
			System.out.println(TextFormat.printer().escapingNonAscii(false).printToString(oRpd.build()));
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
}